package top.wu2020.lazy.ws.chat.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.dromara.hutool.swing.captcha.generator.RandomGenerator;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.wu.framework.web.response.Result;
import org.wu.framework.web.response.ResultFactory;
import org.wu.framework.web.spring.EasyController;
import top.wu2020.lazy.ws.chat.application.MailCodeRecordsApplication;
import top.wu2020.lazy.ws.chat.application.command.mail.MailCheckCommand;
import top.wu2020.lazy.ws.chat.application.command.mail.MailCommand;
import top.wu2020.lazy.ws.chat.application.command.mail.code.records.MailCodeRecordsStoryCommand;

import java.time.LocalDateTime;

@Tag(name = "邮箱发送")
@EasyController("/mail")
public class MailController {

    @Resource
    private JavaMailSenderImpl javaMailSender;

    @Resource
    private MailProperties mailProperties;

    @Resource
    private MailCodeRecordsApplication mailCodeRecordsApplication;


    @PostMapping("/sendVerificationCode")
    public Result<?> sendVerificationCode(@RequestBody MailCommand mailCommand) {
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 6);
        String verificationCode = randomGenerator.generate();
        //简单邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("【haschat】账号注册");//主题
        message.setText(String.format("您正在注册haschat账号，本次请求的邮件验证码是：<b>%s</b>（如非本人操作，请忽略该信息）", verificationCode));
      //接受者邮箱（任何邮箱都可以）
        message.setTo(mailCommand.getEmail());
        //发送者邮箱
        message.setFrom(mailProperties.getUsername());

        MailCodeRecordsStoryCommand mailCodeRecordsStoryCommand = new MailCodeRecordsStoryCommand();
        mailCodeRecordsStoryCommand.setVerificationCode(verificationCode);
        mailCodeRecordsStoryCommand.setEmail(mailCommand.getEmail());
        mailCodeRecordsStoryCommand.setTimestamp(LocalDateTime.now());
        mailCodeRecordsApplication.story(mailCodeRecordsStoryCommand);
        javaMailSender.send(message);
        return ResultFactory.successOf();
    }

    /**
     * 邮箱验证码验证
     *
     * @param mailCheckCommand 验证数据
     * @return 返回结果
     */
    @Operation(summary = "邮箱验证码验证")
    @PostMapping("/checkVerificationCode")
    public Result<?> checkVerificationCode(@RequestBody MailCheckCommand mailCheckCommand) {
        return mailCodeRecordsApplication.checkVerificationCode(mailCheckCommand);
    }

}
